import { Injectable } from '@nestjs/common';
import { CreateBackpackDto } from './dto/create-backpack.dto';
import { UpdateBackpackDto } from './dto/update-backpack.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Backpack } from './entities/backpack.entity';
import { Repository } from 'typeorm';

@Injectable()
export class BackpackService {
  constructor(
    @InjectRepository(Backpack)
    private readonly backpack: Repository<Backpack>,
  ) { }

  create(createBackpackDto: CreateBackpackDto) {
    return 'This action adds a new backpack';
  }

  async findAll() {
    return await this.backpack.find();
  }
  // 出售物品
  async sellArticle(param: { articleId: number, sellNum: number }) {
    const article = await this.backpack.findOne({
      where: {
        articleId: param.articleId
      }
    })
    const gold = await this.backpack.findOne({
      where: {
        articleId: 1
      }
    })
    article.num -= param.sellNum
    gold.num += param.sellNum * article.worth
    await this.backpack.save(gold);
    await this.backpack.save(article);
    return {
      code: 200,
      msg: "出售成功"
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} backpack`;
  }

  update(id: number, updateBackpackDto: UpdateBackpackDto) {
    return this.backpack.update(id, updateBackpackDto);
  }

  async remove(id: number) {
    await this.backpack.delete(id);
    return {
      code: 200,
      msg: "删除成功"
    }
  }
}
